<template>
  <t-dialog
    v-model:visible="dialogVisible"
    :header="$t('common.categorySelector.title')"
    :closeOnEscKeydown="true"
    :closeOnOverlayClick="false"
    width="520px"
  >
    <div class="category-selector">
      <div class="selector-section">
        <div class="section-title">{{ $t('common.categorySelector.selectCategory') }}</div>

        <!-- 分类选择 -->
        <div class="category-tree">
          <div class="tree-level">
            <!-- 一级分类 -->
            <div class="level-title">{{ $t('common.categorySelector.primaryCategory') }}</div>
            <div class="level-items">
              <div
                v-for="category in state.categories.primary"
                :key="category.id"
                class="category-item"
                :class="{ active: state.selected.primary === category.id }"
              >
                <span class="category-text" @click="action.selectCategory('primary', category.id)">
                  {{ category.name }}
                </span>
                <span
                  class="delete-icon-wrapper"
                  @click.stop="action.confirmDeleteCategory('primary', category.id)"
                >
                  <t-icon name="delete" class="delete-icon" />
                </span>
              </div>
              <div class="category-item add-new" @click="action.showNewCategoryInput('primary')">
                <t-icon name="add" />
                {{ $t('common.categorySelector.addNew') }}
              </div>
            </div>
            <t-input
              v-if="state.newCategory.level === 'primary'"
              v-model="state.newCategory.name"
              :placeholder="$t('common.categorySelector.newCategoryPlaceholder')"
              @blur="action.addNewCategory()"
              @keyup.enter="action.addNewCategory()"
              size="small"
              ref="newCategoryInput"
            />
          </div>

          <!-- 二级分类 (仅当选择了一级分类后显示) -->
          <div class="tree-level" v-if="state.selected.primary">
            <div class="level-title">{{ $t('common.categorySelector.secondaryCategory') }}</div>
            <div class="level-items">
              <div
                v-for="category in state.categories.secondary"
                :key="category.id"
                class="category-item"
                :class="{ active: state.selected.secondary === category.id }"
              >
                <span
                  class="category-text"
                  @click="action.selectCategory('secondary', category.id)"
                >
                  {{ category.name }}
                </span>
                <span
                  class="delete-icon-wrapper"
                  @click.stop="action.confirmDeleteCategory('secondary', category.id)">
                  <t-icon name="delete" class="delete-icon" />
                </span>
              </div>
              <div class="category-item add-new" @click="action.showNewCategoryInput('secondary')">
                <t-icon name="add" />
                {{ $t('common.categorySelector.addNew') }}
              </div>
            </div>
            <t-input
              v-if="state.newCategory.level === 'secondary'"
              v-model="state.newCategory.name"
              :placeholder="$t('common.categorySelector.newCategoryPlaceholder')"
              @blur="action.addNewCategory()"
              @keyup.enter="action.addNewCategory()"
              size="small"
              ref="newCategoryInput"
            />
          </div>

          <!-- 三级分类 (仅当选择了二级分类后显示) -->
          <div class="tree-level" v-if="state.selected.secondary">
            <div class="level-title">{{ $t('common.categorySelector.tertiaryCategory') }}</div>
            <div class="level-items">
              <div
                v-for="category in state.categories.tertiary"
                :key="category.id"
                class="category-item"
                :class="{ active: state.selected.tertiary === category.id }"
              >
                <span class="category-text" @click="action.selectCategory('tertiary', category.id)">
                  {{ category.name }}
                </span>
                <span
                  class="delete-icon-wrapper"
                  @click.stop="action.confirmDeleteCategory('tertiary', category.id)">
                  <t-icon name="delete" class="delete-icon" />
                </span>
              </div>
              <div class="category-item add-new" @click="action.showNewCategoryInput('tertiary')">
                <t-icon name="add" />
                {{ $t('common.categorySelector.addNew') }}
              </div>
            </div>
            <t-input
              v-if="state.newCategory.level === 'tertiary'"
              v-model="state.newCategory.name"
              :placeholder="$t('common.categorySelector.newCategoryPlaceholder')"
              @blur="action.addNewCategory()"
              @keyup.enter="action.addNewCategory()"
              size="small"
              ref="newCategoryInput"
            />
          </div>
        </div>
      </div>

      <!-- 预览和确认区域 -->
      <div class="preview-section" v-if="videoPath">
        <video class="preview-video" :src="videoPath" controls />
        <div class="selected-path" v-if="categoryPath">
          {{ categoryPath }}
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <t-button theme="default" variant="outline" @click="action.close">
          {{ $t('common.button.cancel') }}
        </t-button>
        <t-button :loading="state.submitting" :disabled="!canSubmit" @click="action.submit">
          {{ $t('common.button.confirm') }}
        </t-button>
      </div>
    </template>

    <!-- 删除确认对话框 -->
    <t-dialog
      v-model:visible="state.deleteDialog.visible"
      :header="$t('common.categorySelector.deleteConfirmTitle')"
      width="400px"
    >
      <div class="delete-content">
        <p>{{ state.deleteDialog.message }}</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <t-button theme="default" variant="outline" @click="state.deleteDialog.visible = false">
            {{ $t('common.button.cancel') }}
          </t-button>
          <t-button
            theme="danger"
            :loading="state.deleteDialog.loading"
            @click="action.deleteCategory"
          >
            {{ $t('common.button.delete') }}
          </t-button>
        </div>
      </template>
    </t-dialog>
  </t-dialog>
</template>

<script setup>
import { reactive, computed, watch, ref, nextTick } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import {
  getCategoryTree,
  getSubCategories,
  addCategory,
  deleteCategory,
} from '@renderer/api'
import { Client } from '@renderer/client'

const { t } = useI18n()

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  videoPath: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['update:visible', 'sync-complete'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emits('update:visible', val)
})

const newCategoryInput = ref(null)

const state = reactive({
  categories: {
    primary: [],
    secondary: [],
    tertiary: []
  },
  selected: {
    primary: null,
    secondary: null,
    tertiary: null
  },
  newCategory: {
    level: null,
    name: '',
    parentId: null
  },
  deleteDialog: {
    visible: false,
    loading: false,
    categoryId: null,
    categoryLevel: null,
    message: ''
  },
  submitting: false,
  loading: false,
  error: null
})

// 计算属性
const canSubmit = computed(() => {
  // 需要至少选择一级和二级分类
  return state.selected.primary && state.selected.secondary
})

const categoryPath = computed(() => {
  if (!state.selected.primary) return ''

  const primary = state.categories.primary.find((c) => c.id === state.selected.primary)
  if (!primary) return ''

  let path = primary.name

  if (state.selected.secondary) {
    const secondary = state.categories.secondary.find((c) => c.id === state.selected.secondary)
    if (secondary) {
      path += ' / ' + secondary.name

      if (state.selected.tertiary) {
        const tertiary = state.categories.tertiary.find((c) => c.id === state.selected.tertiary)
        if (tertiary) {
          path += ' / ' + tertiary.name
        }
      }
    }
  }

  return path
})

// 在对话框打开时加载分类数据
watch(
  () => props.visible,
  async (newVal) => {
    if (newVal) {
      try {
        state.loading = true
        state.error = null
        await action.loadCategories()
      } catch (err) {
        state.error = err.message || '加载分类失败'
        MessagePlugin.error(t('common.message.loadCategoriesError'))
        console.error('加载分类错误:', err)
      } finally {
        state.loading = false
      }
    }
  },
  { immediate: true }
)

const action = {
  async loadCategories() {
    try {
      const response = await getCategoryTree()

      // 处理服务器返回的数据结构
      if (!response || !response.data) {
        throw new Error('获取分类数据失败')
      }

      // 假设服务器返回的数据结构为 { data: [...分类列表] }
      state.categories.primary = response.data.map((item) => ({
        id: item.id,
        name: item.name,
        level: 1
      }))

      // 重置选择和其他级别分类
      state.selected.primary = null
      state.selected.secondary = null
      state.selected.tertiary = null
      state.categories.secondary = []
      state.categories.tertiary = []

    } catch (err) {
      console.error('加载分类树错误:', err)
      throw err
    }
  },

  async selectCategory(level, categoryId) {
    state.selected[level] = categoryId

    if (level === 'primary') {
      // 重置二级和三级分类的选择
      state.selected.secondary = null
      state.selected.tertiary = null
      state.categories.tertiary = []

      // 加载二级分类
      try {
        const response = await getSubCategories(categoryId)

        // 确保响应有效
        if (!response || !response.data) {
          throw new Error('获取二级分类失败')
        }

        state.categories.secondary = response.data.map((item) => ({
          id: item.id,
          name: item.name,
          level: 2
        }))

      } catch (err) {
        console.error('加载二级分类错误:', err)
        MessagePlugin.error('加载二级分类失败')
      }
    } else if (level === 'secondary') {
      // 重置三级分类的选择
      state.selected.tertiary = null

      // 加载三级分类
      try {
        const response = await getSubCategories(categoryId)

        // 确保响应有效
        if (!response || !response.data) {
          throw new Error('获取三级分类失败')
        }

        state.categories.tertiary = response.data.map((item) => ({
          id: item.id,
          name: item.name,
          level: 3
        }))

      } catch (err) {
        console.error('加载三级分类错误:', err)
        MessagePlugin.error('加载三级分类失败')
      }
    }
  },

  showNewCategoryInput(level) {
    state.newCategory.level = level
    state.newCategory.name = ''

    // 设置父分类ID
    if (level === 'primary') {
      state.newCategory.parentId = 0 // 一级分类没有父级
    } else if (level === 'secondary') {
      state.newCategory.parentId = state.selected.primary
    } else if (level === 'tertiary') {
      state.newCategory.parentId = state.selected.secondary
    }

    // 聚焦到输入框
    nextTick(() => {
      if (newCategoryInput.value) {
        newCategoryInput.value.focus()
      }
    })
  },

  async addNewCategory() {
    if (!state.newCategory.name.trim()) {
      state.newCategory.level = null
      return
    }

    const { level, name, parentId } = state.newCategory

    try {
      // 添加新分类
      const levelNum = level === 'primary' ? 1 : level === 'secondary' ? 2 : 3

      const response = await addCategory(name, parentId, levelNum)

      if (!response || !response.data) {
        throw new Error('添加分类失败')
      }

      const newCategory = {
        id: response.data.id,
        name: response.data.name,
        level: levelNum
      }

      // 添加到列表并选中
      state.categories[level].push(newCategory)

      // 延迟执行选择，确保UI更新
      nextTick(() => {
        action.selectCategory(level, newCategory.id)
      })

      MessagePlugin.success(t('common.message.addCategorySuccess'))
    } catch (err) {
      MessagePlugin.error(t('common.message.addCategoryError') + ': ' + (err.message || '未知错误'))
      console.error('添加分类错误:', err)
    }

    // 重置新分类状态
    state.newCategory.level = null
    state.newCategory.name = ''
  },

  // 显示删除确认对话框
  confirmDeleteCategory(level, categoryId) {
    // 获取分类名称
    const category = state.categories[level].find((c) => c.id === categoryId)
    if (!category) return

    state.deleteDialog.categoryId = categoryId
    state.deleteDialog.categoryLevel = level

    // 设置确认消息
    let message = ''
    if (level === 'primary') {
      message = t('common.categorySelector.deletePrimaryConfirm', { name: category.name })
    } else if (level === 'secondary') {
      message = t('common.categorySelector.deleteSecondaryConfirm', { name: category.name })
    } else {
      message = t('common.categorySelector.deleteTertiaryConfirm', { name: category.name })
    }

    state.deleteDialog.message = message
    state.deleteDialog.visible = true
  },

  // 执行删除分类操作
  async deleteCategory() {
    if (!state.deleteDialog.categoryId || !state.deleteDialog.categoryLevel) {
      return
    }

    const { categoryId, categoryLevel } = state.deleteDialog

    try {
      state.deleteDialog.loading = true

      const response = await deleteCategory(categoryId)

      if (!response || response.code !== 200) {
        throw new Error(response?.message || '删除分类失败')
      }

      // 从列表中移除
      const index = state.categories[categoryLevel].findIndex((c) => c.id === categoryId)
      if (index !== -1) {
        state.categories[categoryLevel].splice(index, 1)
      }

      // 如果删除的是当前选中的分类，则重置选择
      if (state.selected[categoryLevel] === categoryId) {
        state.selected[categoryLevel] = null

        // 如果删除的是一级分类，则清空二级和三级分类
        if (categoryLevel === 'primary') {
          state.categories.secondary = []
          state.categories.tertiary = []
          state.selected.secondary = null
          state.selected.tertiary = null
        }
        // 如果删除的是二级分类，则清空三级分类
        else if (categoryLevel === 'secondary') {
          state.categories.tertiary = []
          state.selected.tertiary = null
        }
      }

      MessagePlugin.success(t('common.message.deleteCategorySuccess'))
    } catch (err) {
      console.error('删除分类错误:', err)
      MessagePlugin.error(
        t('common.message.deleteCategoryError') + ': ' + (err.message || '未知错误')
      )
    } finally {
      state.deleteDialog.loading = false
      state.deleteDialog.visible = false
      state.deleteDialog.categoryId = null
      state.deleteDialog.categoryLevel = null
    }
  },

  async submit() {
    if (!props.videoPath) {
      MessagePlugin.error(t('common.message.noVideoToSync'))
      return
    }

    if (!canSubmit.value) {
      MessagePlugin.warning(t('common.message.selectCategoryFirst'))
      return
    }

    state.submitting = true

    try {
      // 获取视频文件对象
      const videoFile = await Client.file.getFileObjectFromPath(props.videoPath)

      if (!videoFile) {
        throw new Error('无法获取视频文件')
      }

      // 获取相关分类信息
      const primaryCategory = state.categories.primary.find((c) => c.id === state.selected.primary)
      const secondaryCategory = state.categories.secondary.find(
        (c) => c.id === state.selected.secondary
      )
      const tertiaryCategory = state.selected.tertiary
        ? state.categories.tertiary.find((c) => c.id === state.selected.tertiary)
        : null

      // 准备上传参数
      // const params = {
      //   file: videoFile,
      //   title: `Video-${new Date().getTime()}`,
      //   description: '',
      //   primaryCategoryId: state.selected.primary,
      //   secondaryCategoryId: state.selected.secondary,
      //   tertiaryCategoryId: state.selected.tertiary || 0
      // }

      // console.log('上传视频参数:', params)
      //
      // // 调用上传视频接口
      // const response = await uploadToVideoLibrary(params)
      //
      // console.log('上传视频响应:', response)
      //
      // if (!response || !response.success) {
      //   throw new Error(response?.message || '同步失败')
      // }

      // 同步成功
      emits('sync-complete', {
        success: true,
        categoryInfo: {
          primaryCategoryId: state.selected.primary,
          secondaryCategoryId: state.selected.secondary,
          tertiaryCategoryId: state.selected.tertiary,
          primaryCategoryName: primaryCategory?.name || '',
          secondaryCategoryName: secondaryCategory?.name || '',
          tertiaryCategoryName: tertiaryCategory?.name || '',
          categoryPath: categoryPath.value
        },
        file: videoFile,
      })

      action.close()
    } catch (err) {
      console.error('同步视频错误:', err)
      MessagePlugin.error(t('common.message.syncVideoError') + ': ' + (err.message || '未知错误'))
      emits('sync-complete', { success: false })
    } finally {
      state.submitting = false
    }
  },

  close() {
    dialogVisible.value = false
  }
}
</script>

<style lang="less" scoped>
.category-selector {
  display: flex;
  flex-direction: column;
  max-height: 500px;
  overflow-y: auto;

  .selector-section {
    margin-bottom: 16px;

    .section-title {
      font-weight: 500;
      font-size: 14px;
      color: #ffffff;
      margin-bottom: 12px;
    }

    .category-tree {
      .tree-level {
        margin-bottom: 16px;

        .level-title {
          font-size: 13px;
          color: rgba(255, 255, 255, 0.7);
          margin-bottom: 8px;
        }

        .level-items {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          margin-bottom: 8px;

          .category-item {
            display: flex;
            align-items: center;
            padding: 5px 12px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
            font-size: 12px;
            color: rgba(255, 255, 255, 0.9);
            transition: all 0.2s;

            .category-text {
              cursor: pointer;
            }

            .delete-icon {
              margin-left: 4px;
              opacity: 0.5;
              cursor: pointer;
              font-size: 14px;

              &:hover {
                opacity: 1;
                color: #ff4d4f;
              }
            }

            &:hover {
              background: rgba(67, 74, 249, 0.5);
            }

            &.active {
              background: #434af9;
              color: #ffffff;
            }

            &.add-new {
              display: flex;
              align-items: center;
              gap: 4px;
              background: rgba(255, 255, 255, 0.05);
              border: 1px dashed rgba(255, 255, 255, 0.3);
              cursor: pointer;

              &:hover {
                background: rgba(255, 255, 255, 0.1);
                border-color: rgba(255, 255, 255, 0.5);
              }
            }
          }
        }
      }
    }
  }

  .preview-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    padding-top: 16px;

    .preview-video {
      max-width: 100%;
      max-height: 200px;
      margin-bottom: 12px;
      border-radius: 4px;
      overflow: hidden;
    }

    .selected-path {
      font-size: 13px;
      color: rgba(255, 255, 255, 0.8);
      padding: 8px 12px;
      background: rgba(67, 74, 249, 0.2);
      border-radius: 4px;
      text-align: center;
    }
  }
}

.delete-content {
  p {
    font-size: 14px;
    color: #ffffff;
    margin: 8px 0;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
